<?php

namespace Service\Util;

use mysqli;
use Service\Http\Exception\ModelException;
use Service\Http\Exception\RestException;

trait Database
{
    /**
     * @var mysqli $connection
     */
    private $connection;

    /**
     * @throws RestException
     */
    protected function connect()
    {
        $con = mysqli_connect('localhost', 'root', '', 'book_store');
        if ($con === false) {
            throw new ModelException('数据库连接失败');
        }
        $charset_result = mysqli_set_charset($con, 'utf8mb4');
        if ($charset_result === false) {
            throw new ModelException('数据库字符集修改失败');
        }
        $this->connection = $con;
    }

    /**
     * @throws RestException
     */
    protected function executeSql($sql)
    {
        if ($this->connection === null) {
            $this->connect();
        }
        if (($result = $this->connection->query($sql)) === false) {
            echo mysqli_error($this->connection);
            throw new ModelException('数据库语句执行失败');
        }
        return $result;
    }

    protected function close()
    {
        if ($this->connection !== null) {
            mysqli_close($this->connection);
        }
    }
}
